﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;

namespace Smart.SignalRServer
{
    public class CommonMethod
    {
        public static T FromJsonTo<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString.Replace("\0", ""))))
            {
                T jsonObject = (T)ser.ReadObject(ms);
                return jsonObject;
            }
        }

        #region 获取IP
        /// <summary>
        /// 获取IP
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ip)) { ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; }
            if (string.IsNullOrEmpty(ip)) { ip = HttpContext.Current.Request.UserHostAddress; }
            if (string.IsNullOrEmpty(ip) || ip == "::1") { ip = "127.0.0.1"; }
            return ip;
        }
        #endregion
    }
}